<template>
  <a-modal
    :title="title"
    width="1000px"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    cancelText="关闭">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button @click="handleOk" type="primary" v-if="!disabled">确认</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-divider style="font-weight: 600;margin-top: 20px;" orientation="left">基础信息</a-divider>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="费用预算类型"
            >
              <cn-dict-select-tag :options="{value:'dictDataCode',label:'dictDataDesc'}"
                                 :triggerChange="true"
                                 dictCode="budget_type"
                                 v-decorator="['budgetType',{rules: [{ required: true, message: '请选择' }]}]"
                                 placeholder="请选择"
                                 :disabled="disabled"
                                 @change="budgetType"
              />
            </a-form-item>
          </a-col>

          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="预算年份"
            >
              <a-select v-decorator="['budgetYear',{rules: [{ required: true, message: '请选择费用预算年份' }]}]"
                        placeholder="请选择费用预算年份" :disabled="disabled" @change="getYearQuMonth(1)">
                <a-select-option v-for="(v,i) in yearOp" :key="i" :value="v">
                  {{ v }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="预算季度"
            >
              <!--              @change='changeSelectQuarter'-->
              <a-select v-decorator="['budgetQuarter']" placeholder="请选择费用预算季度" :disabled="disabled"
                        @change="getYearQuMonth(2)">
                <a-select-option v-for="(v,i) in quarterOp" :key="i" :value="v.value">
                  {{ v.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="预算月份"
            >
              <a-select v-decorator="['budgetMonth']" placeholder="请选择费用预算月份" :disabled="disabled">
                <a-select-option v-for="(v,i) in monthOp" :key="i" :value="v.value">
                  {{ v.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-divider style="font-weight: 600;margin-top: 20px;" orientation="left">预算详情</a-divider>
          <span v-if="type==1">
            <a-col :md="12" :sm="24">
              <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="企业组织"
              >
                 <j-tree-select
                   v-if="visible"
                   v-decorator="['budgetOrgCode',{rules: [{ required: true, message: '请选择企业组织' }]}]"
                   placeholder="请选择企业组织"
                   ref="companyChose"
                   data-type="org"
                   :disabled="disabled"
                   @change="(e,v)=>changeJselect('budgetOrgCode',v)"
                 />
              </a-form-item>
            </a-col>
          </span>
          <span v-if="type==2">
            <a-col :md="12" :sm="24">
              <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="客户"
              >
                 <j-select-cust v-decorator="['custName',{rules: [{ required: true, message: '请选择客户' }]}]"
                                :multiple="false" :disabled="disabled"
                                @select="(row)=>selectRole(row,'custCode','custName')"/>
              </a-form-item>
            </a-col>
          </span>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="商品层级"
            >
              <j-tree-select
                v-if="visible"
                v-decorator="['productLevelCode']"
                placeholder="请选择商品层级"
                ref="productLevelCode"
                data-type="product_type"
                :disabled="disabled"
                @change="(e,v)=>changeJselect('productLevelCode',v)"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="商品"
            >
              <a-input-search v-decorator="['productName']" :disabled="disabled"
                              enter-button placeholder='请选择商品' readOnly @search="productSearch('product')" />
              <a-input v-decorator="['productCode', {}]" type='hidden' />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="预算科目"
            >
              <j-select-subjects v-decorator="['budgetSubjectsName',{rules: [{ required: true, message: '请选择预算科目' }]}]"
                                 :multiple="false" :disabled="disabled" :buttons="false"
                                 @select="(row)=>selectRole2(row,'budgetSubjectsCode')"/>
              <a-input type="hidden" v-decorator="['budgetSubjectsCode']"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="初期金额"
            >
              <a-input placeholder="请输入初期金额"
                       v-decorator="['initAmount',{rules: [{ required: true, message: '请输入初期金额' }]}]"
                       :disabled="disabled"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="备注"
            >
              <a-input placeholder="请输入备注" v-decorator="['remarks']" :disabled="disabled"/>
            </a-form-item>
          </a-col>

        </a-row>
      </a-form>
    </a-spin>
    <proChose ref='prochoose' v-bind='modalProps' @okbro='okbropro'></proChose>

  </a-modal>
</template>

<script>
import { getAction, httpAction, postAction } from '@/api/manage'
import { pick } from 'lodash'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import JAreaLinkage from '@comp/cn-form/CnAreaLinkage'
import UploadImage from '@/components/upload-image/UploadImage'
import JImageUpload from '@/components/cn-form/JImageUpload'
import JSelectSubjects from '@/components/cn-select-popup/JSelectSubjects'
import JSelectCust from '@/components/cn-select-popup/CnSelectCust'
import JSelectProduct from '@/components/cn-select-popup/JSelectProduct'
import JDictSelectTag from '@comp/dict/CnDictSelectTag'
import proChose from '@comp/cn-components/ProChose'


export default {
  name: 'terminal-modal',
  data() {
    return {
      type: 1,
      disabled: false,
      detailPage: false,
      title: '操作',
      visible: false,
      model: {},
      ptQueryParam: {},

      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      subOp: [],
      yearOp: [],
      quarterOp: [],
      monthOp: [],
      getYear: window._CONFIG['domianTpmURL'] + '/budget/tpmBudgetFee/findFiscalYearList',
      addOrUpdateUrl: window._CONFIG['domianTpmURL'] + '/budget/tpmBudgetFee/saveEntity'

    }
  },
  components: {
    JTreeSelect,
    JAreaLinkage,
    UploadImage,
    JImageUpload,
    JSelectSubjects,
    JSelectCust,
    JSelectProduct,
    JDictSelectTag,
    proChose
  },

  created() {
    // // 生成预算年度
    // let nowYear=new Date().getFullYear()
    // let op=[]
    // for (let i=0;i<=10;i++){
    //   op.push({name:nowYear+i,value:nowYear+i})
    // }
    // this.yearOp=op
    let quarter = [
      {
        name: '一季度',
        value: 1
      },
      {
        name: '二季度',
        value: 2
      },
      {
        name: '三季度',
        value: 3
      },
      {
        name: '四季度',
        value: 4
      }
    ]

    this.quarterList = quarter
    // let monthList={
    //   1:[
    //     {
    //       name:'01',
    //       value:'01'
    //     },{
    //       name:'02',
    //       value:'02'
    //     },{
    //       name:'03',
    //       value:'03'
    //     }],
    //   2:[
    //     {
    //       name:'04',
    //       value:'04'
    //     },{
    //       name:'05',
    //       value:'05'
    //     },{
    //       name:'06',
    //       value:'06'
    //     }],
    //   3:[
    //     {
    //       name:'07',
    //       value:'07'
    //     },{
    //       name:'08',
    //       value:'08'
    //     },{
    //       name:'09',
    //       value:'09'
    //     }],
    //   4:[
    //     {
    //       name:'10',
    //       value:'10'
    //     },{
    //       name:'11',
    //       value:'11'
    //     },{
    //       name:'12',
    //       value:'12'
    //     }],
    // }
    //
    // this.monthList=monthList
    // // 生成预算月度
    let month = [
      {
        name: '01',
        value: '01'
      }, {
        name: '02',
        value: '02'
      }, {
        name: '03',
        value: '03'
      }, {
        name: '04',
        value: '04'
      }, {
        name: '05',
        value: '05'
      }, {
        name: '06',
        value: '06'
      }, {
        name: '07',
        value: '07'
      }, {
        name: '08',
        value: '08'
      }, {
        name: '09',
        value: '09'
      }, {
        name: '10',
        value: '10'
      }, {
        name: '11',
        value: '11'
      }, {
        name: '12',
        value: '12'
      }]
    this.monthList = month
    // postAction(window._CONFIG['domianTpmURL']+ "/budget/tpmBudgetSubjects/findPageList",{current:1,size:100}).then(res=>{
    //   if(res.success){
    //     let op=[]
    //     res.result.records.map(v=>{
    //       op.push({name:v.subjectsName,value:v.subjectsCode})
    //     })
    //     this.subOp=op
    //   }
    // })

  },

  watch: {
    // 'model.productLevelName'(val){
    //     this.handleQueryParms()
    // }

  },
  methods: {
    // handleQueryParms(){
    //
    // },
    add() {
      this.edit({})
    },
    edit(record, status) {
      if (record.budgetType == 2) {
        this.type = 2
      } else {
        this.type = 1
      }
      this.disabled = false
      this.form.resetFields()
      this.visible = true
      this.model = {}
      if (record.id) {
        this.model = Object.assign({}, record)
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))

        })
      }
      this.getYearQuMonth()
    },

    close() {
      this.visible = false
      this.$emit('close')
    },
    handleCancel() {
      this.close()
      this.model = {}
    },
    productSearch(status) {
      this.$refs.prochoose.rowKey = 'goodsCode'
      let formconfig = [
        {
          key: 'goodsCode',
          label: '商品编码'
        },
        {
          key: 'goodsName',
          label: '商品名称'
        }
      ]
      let tableconfig = {
        columns: [
          {
            title: '商品编码',
            align: 'center',
            dataIndex: 'goodsCode',
            width: 120,
            ellipsis: true
          },
          {
            title: '商品名称',
            align: 'center',
            dataIndex: 'goodsName',
            width: 120,
            ellipsis: true
          }
        ],
        list: window._CONFIG['domianURL'] + '/goods/cnGoods/findPageList',
        multiple: false,
        columW: 11,
        name:'商品'
      }
      this.name = '商品'
      this.$refs.prochoose.edit(formconfig, tableconfig, status)
    },
    okbropro(record, status) {
      let res = record[0]
      console.log(res.goodsCode)
      if (status == 'product') {
        this.form.setFieldsValue({
          productName: res.goodsName,
          productCode: res.goodsCode
        })
      }
    },
    handleOk() {
      const that = this
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          let formData = Object.assign({}, this.model, values)
          formData.custName = this.model.custName
          postAction(this.addOrUpdateUrl, formData).then(res => {
            if (!res.success) {
              that.$message.error(res.message)
              that.confirmLoading = false
              return
            }
            that.confirmLoading = false
            that.$emit('ok')
            that.handleCancel()
            that.$message.success(res.message)
          })
        }
      })
    },
    changeSelect(options, name, event) {
      name = name.split('Code')
      if (name.length > 1) {
        name = name[0] + 'Name'
        let item = options.find(item => item.value == event)
        this.model[name] = item.name
      }
    },
    selectRole2(e1, e2) {
      if (e2 == 'productName') {
        if (e1.length == 0) {
          return
        }
        this.form.setFieldsValue({
          productCode: e1[0].matnr,
          productName: e1[0].maktx
        })
      } else if (e2 == 'budgetSubjectsCode') {
        this.form.setFieldsValue({
          budgetSubjectsCode: e1[0].subjectsCode,
          budgetSubjectsName: e1[0].subjectsName
        })
      }
    },
    selectRole(row, name, key) {
      console.log(row)
      let value = row.map(v => v[key])
      name = name.split('Code')
      if (name.length >= 1) {
        name = name[0] + 'Name' + (name[1] ? name[1] : '')
        this.model[name] = value + ''
        this.model.custCode = row[0].custCode
      }
    },

    getYearQuMonth(key) {
      let _this = this

      this.$nextTick(() => {
        if (key == 1) {
          _this.quarterOp = []
          _this.monthOp = []
          this.form.resetFields(['budgetQuarter'])
          this.form.resetFields(['budgetMonth'])
        }
        if (key == 2) {
          this.form.resetFields(['budgetMonth'])
          _this.monthOp = []
        }

        let year = this.form.getFieldValue('budgetYear')
        let quarter = this.form.getFieldValue('budgetQuarter')
        postAction(this.getYear, { bgQuarter: quarter, bgYear: year }).then(res => {
          if (res.success) {
            let list = []

            if (!year && !quarter) {
              if (res.result.length > 0) {
                _this.yearOp = res.result
              } else {
                _this.$message.info('请先增加预算财年')
              }
              return
            }
            if (year && !quarter) {
              res.result.map(v => {
                let item = _this.quarterList.find(item => item.value == v)
                if (item) {
                  list.push(item)
                }
              })

              _this.quarterOp = list
            }
            if (year && quarter) {
              res.result.map(v => {
                let item = _this.monthList.find(item => item.value == v)
                if (item) {
                  list.push(item)
                }
              })

              _this.monthOp = list
            }

          }
        })
      })
    },

    changeJselect(name, value) {
      if (name == 'productLevelCode') {
        this.form.resetFields('productCode')
        this.model.productName = ''
        this.$nextTick(() => {
          this.ptQueryParam = { typeCode: this.form.getFieldValue('productLevelCode') }
        })
      }
      name = name.split('Code')
      if (name.length > 1) {
        name = name[0] + 'Name' + (name[1] ? name[1] : '')
        this.model[name] = value
      }
    },
    budgetType(e, v) {
      this.type = e
    },
    changeSelectQuarter(e) {
      this.monthOp = this.monthList[e]
    }
  }
}
</script>

<style scoped>
.gonghuoxinxi {
  width: 100%;
  border-bottom: 1px dashed black;
  margin: 10px 0;
  padding: 15px 5px;
  display: flex;
  flex-direction: column;
}

/deep/ .ant-modal-body {
  padding: 0px;
}

</style>
